<template>
  <div v-loading="loading" class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ page.total }}条记录</span>
        <template slot="after">
          <el-button
            size="small"
            type="warning"
            @click="$router.push({ path: '/import' })"
          >导入</el-button>
          <el-button
            size="small"
            type="danger"
            @click="exportExcel"
          >导出</el-button>
          <el-button
            size="small"
            type="primary"
            @click="showDialog = true"
          >新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card v-loading="loading">
        <el-table border :data="list">
          <el-table-column label="序号" sortable="">
            <template
              slot-scope="scope"
            >{{ (page.page - 1) * page.size + scope.$index + 1 }}
            </template>
          </el-table-column>
          <!-- <el-table-column label="序号" sortable="" type="index" /> -->
          <el-table-column label="头像" sortable="">
            <template slot-scope="scope">
              <img
                v-imgerror="require('@/assets/common/head.jpg')"
                class="staffPhoto"
                :src="scope.row.staffPhoto"
                alt=""
                @click="showCodeDialog(scope.row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column
            label="聘用形式"
            sortable=""
            prop="formOfEmployment"
            :formatter="formatEmployment"
          />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template slot-scope="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template slot-scope="{ row }">
              <!-- 根据当前状态来确定 是否打开开关 -->
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="deleteEmployee(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.total"
            :page-size="page.size"
            :current-page="page.page"
            :page-sizes="[5, 10, 20, 40]"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <AddDemployee :show-dialog.sync="showDialog" />
      <AssignRole ref="assignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
      <el-dialog title="二维码" :visible="isShowCode" @close="isShowCode = false">
        <el-row type="flex" justify="center" align="middle">
          <canvas ref="mycanvas" />
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import QRcode from 'qrcode'
import AddDemployee from './components/add-employee'
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import { formatDate } from '@/filters'
import AssignRole from '@/views/employees/components/assign-role'
export default {
  components: {
    AddDemployee,
    AssignRole
  },
  data() {
    return {
      userId: '',
      showRoleDialog: false,
      showDialog: false,
      loading: false,
      list: [], // 接数据的
      page: {
        page: 1, // 当前页码
        size: 5,
        total: 0 // 总数
      },
      isShowCode: false
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // show() {
    //   this.value = !this.value
    // },
    showCodeDialog(imgUrl) {
      console.log(imgUrl)
      console.log('clickk')
      if (imgUrl) {
        this.isShowCode = true
      }
      // 我们想等待弹窗出现之后再生成
      // 简单粗暴就是定时器
      // setTimeout(() => {
      //   QRcode.toCanvas(this.$refs.mycanvas, imgUrl)
      // }, 200)
      // vue 也提供了一个方法, 如果你修改了一个变量会导致页面渲染
      // 你希望等待页面渲染完之后执行某些操作, 可以使用 this.$nextTick
      this.$nextTick(() => {
        QRcode.toCanvas(this.$refs.mycanvas, imgUrl)
      })
    },
    async getEmployeeList() {
      this.loading = true
      const { total, rows } = await getEmployeeList(this.page)
      this.page.total = total
      this.list = rows
      this.loading = false
    },
    handleSizeChange(val) {
      this.page.size = val
      this.getEmployeeList()
    },
    handleCurrentChange(val) {
      this.page.page = val
      this.getEmployeeList()
    },
    formatEmployment(row, column, cellValue, index) {
      const list = EmployeeEnum.hireType // 获取枚举数组
      const obj = list.find((item) => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    // formatEmploy(row, column, cellValue, index) {
    //   const list = EmployeeEnum.stausInfos // 获取枚举数组
    //   const obj = list.find(item => Number(item.id) === cellValue)
    //   return obj ? obj.value : '未知'
    // },
    async deleteEmployee(id) {
      try {
        await this.$confirm('您确定删除该员工吗')
        await delEmployee(id)
        this.getEmployeeList()
        this.$message.success('删除成功')
      } catch (err) {
        console.log(err)
      }
    },
    // 这两个参数 header 和 item 是用来生成数组的重要依赖
    // 不过不是这里单独编写, 应该从调用的地方传入
    translateKey(item, headers) {
      const arr = []

      for (const key in headers) {
        const enket = headers[key]

        if (enket === 'timeOfEntry' || enket === 'correctionTime') {
          arr.push(formatDate(item[headers[key]], 'yyyy/MM/dd'))
        } else {
          arr.push(item[headers[key]])
        }
      }
      return arr
    },
    async exportExcel() {
      const { rows } = await getEmployeeList({
        page: 1,
        size: this.page.total
      })
      const headers = {
        手机号: 'mobile',
        姓名: 'username',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }
      const arr = rows.map((item) => {
        return this.translateKey(item, headers)
      })
      import('@/vendor/Export2Excel').then((excel) => {
        excel.export_json_to_excel({
          header: Object.keys(headers), // 表头 必填
          data: arr, // 具体数据 必填
          filename: '员工信息表',
          autoWidth: true,
          bookType: 'xlsx'
          // filename: 'excel-list', // 非必填
          // autoWidth: true, // 非必填
          // bookType: 'xlsx' // 非必填
        })
      })
    },
    async editRole(id) {
      this.userId = id
      await this.$refs.assignRole.getUserDetailById(id) // 父组件调用子组件方法
      this.showRoleDialog = true
    }
  }
}
</script>

<style lang="scss" scoped>
.staffPhoto {
  width: 100px;
  height: 100px;
  object-fit: cover;
}
</style>

